package com.itheima.controller;

import com.itheima.domain.system.SysLog;
import com.itheima.domain.system.User;
import com.itheima.service.impl.system.SysLogServiceImpl;
import com.itheima.service.system.SysLogService;
import com.itheima.utils.IdUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BaseServlet extends HttpServlet {
    private SysLogService sysLogService = new SysLogServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        //设置请求的字符集编码为 utf-8
        req.setCharacterEncoding("UTF-8");
        SysLog sysLog = new SysLog();
        Long executionTime = sysLog.getExecutionTime();
        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        if ("login".equals(methodName)||"logout".equals(methodName)) {
            //login 放行
        } else {
            //非login 需登录
            if (user !=null && StringUtils.isNotBlank(user.getUsername())){

            }else{
                resp.sendRedirect(req.getContextPath()+"/after_filter.jsp");
                return;
            }
        }
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Long start = System.currentTimeMillis();
            method.setAccessible(true);
            method.invoke(this, req, resp);
            Long end = System.currentTimeMillis();
            executionTime = end - start;
        } catch (Exception e) {
            e.printStackTrace();
        }

        sysLog.setId(IdUtil.getId());

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        sysLog.setVisitTimeStr(time);


        StringBuffer url = req.getRequestURL();//url=http://localhost:82/system/syslog/list
        String URL = url.toString();
        sysLog.setUrl(URL);
        sysLog.setExecutionTime(executionTime);
        sysLog.setMethod(methodName);
        String ip = req.getRemoteAddr();
        sysLog.setIp(ip);
        if (user != null)
            sysLog.setUsername(user.getUsername());
        //所有遍历和日志(除了删除)操作不记录
        if (uri.contains("syslog/list")||uri.contains("list")) {
            System.out.println("======查看日志=======");
        } else {
            sysLogService.save(sysLog);
        }
    }
}
